package java_thinking.unit_21.Exercise.thread.pool;

import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * @Desc:   ForkJoinPool 分治线程池
 * @author: cww
 * @DateTime: 2020-04-06 11:09
 */

public class ForkJoinTest {

    private static ForkJoinPool forkJoinPool = new ForkJoinPool(4);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int[] intArray = IntStream.rangeClosed(0,200000000).toArray();
        Future<Integer> future = forkJoinPool.submit(new ForkTask(0,intArray.length,intArray));
        System.out.println(future.get());
        forkJoinPool.shutdown();
    }

    static class ForkTask extends RecursiveTask<Integer>{
        /**
         * 默认分割粒度
         */
        private static final int THRESHOLD = 1000;
        private int higth,low;
        private int[] array;

        public ForkTask(int low, int high, int[] array) {
            this.higth = high;
            this.low = low;
            this.array = array;
        }

        @Override
        protected Integer compute() {
            if ((higth - low) <= THRESHOLD){
                int sum = 0;
                for (int i = low; i < higth; i++) {
                    sum += array[i];
                }
                return sum;
            } else {
                int mid = (higth - low)/2+low;
                // left fork
                ForkJoinTask leftTask = new ForkTask(low, mid, array);
                ForkJoinTask rightTask = new ForkTask(mid,higth,array);
                invokeAll(leftTask,rightTask);
                return ((ForkTask) leftTask).join() + ((ForkTask) rightTask).join();
            }
        }
    }
}

